package com.example.sppmode;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.example.sppmode.Common.AllParam;
import com.example.sppmode.Common.DataConfig;
import com.example.sppmode.Common.PairedDeviceInfo;
import com.example.sppmode.DataAccess.MyData;
import com.example.sppmode.DataProtocol.CommandDataAnalyze;
import com.example.sppmode.DataProtocol.CommandInfo;
import com.example.sppmode.DeviceConnectMgr.SPPEventListener;
import com.example.sppmode.DeviceConnectMgr.SppConnMgr;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;


public class BLESPPUtils {
    public enum BatteryStatus {
        NOT_CHARGING(0),  // 未充电
        CHARGING(1),      // 充电中
        FULLY_CHARGED(2);  // 充满电
        private final int code;

        // 构造函数
        BatteryStatus(int code) {
            this.code = code;
        }
        // 获取关联的整数值
        public int getCode() {
            return code;
        }

        // 根据整数值获取枚举
        public static BatteryStatus fromCode(int code) {
            for (BatteryStatus status : BatteryStatus.values()) {
                if (status.getCode() == code) {
                    return status;
                }
            }
            throw new IllegalArgumentException("Invalid code: " + code);
        }
    }

    private static final int MESSAGE_DATA_RECEIVED = 1;
    FunctionBlueToothCame.BlueToothCameData blueToothCameData = new FunctionBlueToothCame.BlueToothCameData();
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MESSAGE_DATA_RECEIVED) {
                // 从消息中获取数据
                byte[] data = (byte[]) msg.obj; // 获取 byte[] 数据
                int length = msg.arg1; // 获取长度

                byte[] dataNow = FunctionBlueToothCame.concat(blueToothCameData.data, blueToothCameData.dataLen, data, length);
                blueToothCameData = FunctionBlueToothCame.parasBlueToothCame(dataNow, mOnBluetoothAction);

            }
        }
    };

    private Handler handlerBattery = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MESSAGE_DATA_RECEIVED) {
                // 从消息中获取数据
                byte[] data = (byte[]) msg.obj; // 获取 byte[] 数据
                int length = msg.arg1; // 获取长度

                String[] receive = byteToHex(data, length); //byte数组转为string数组,16进制
                int battery = data[9] & 0xFF; //电量
                BatteryStatus status = BatteryStatus.fromCode(data[6] & 0xFF);//充电状态
                mOnBluetoothAction.onReceiveBattery(receive, battery, status);

            }
        }
    };

    private Handler handlerUseMode = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MESSAGE_DATA_RECEIVED) {
                // 从消息中获取数据
                byte[] data = (byte[]) msg.obj; // 获取 byte[] 数据
                int length = msg.arg1; // 获取长度

                String[] receive = byteToHex(data, length); //byte数组转为string数组,16进制
                int useMode = ((data[6] & 0xFF) << 8) | (data[7] & 0xFF); //耳机使用模式
                mOnBluetoothAction.onReceiveUseMode(receive, useMode);

            }
        }
    };

    private Handler handlerLabel = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MESSAGE_DATA_RECEIVED) {
                // 从消息中获取数据
                byte[] data = (byte[]) msg.obj; // 获取 byte[] 数据
                int length = msg.arg1; // 获取长度

                String[] receive = byteToHex(data, length); //byte数组转为string数组,16进制
                int label = ((data[6] & 0xFF) << 24) | ((data[7] & 0xFF) << 16) | ((data[8] & 0xFF) << 8) | (data[9] & 0xFF);
                mOnBluetoothAction.onReceiveLabel(receive, label);

            }
        }
    };

    private Handler handlerCameraInfo = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MESSAGE_DATA_RECEIVED) {
                // 从消息中获取数据
                byte[] data = (byte[]) msg.obj; // 获取 byte[] 数据
                int length = msg.arg1; // 获取长度

                String[] receive = byteToHex(data, length); //byte数组转为string数组,16进制

                int picW = ((data[6] & 0xFF) << 8) | (data[7] & 0xFF); //图片宽度
                int picH = ((data[8] & 0xFF) << 8) | (data[9] & 0xFF); //图片高度
                int picLen = ((data[10] & 0xFF) << 24) | (data[11] & 0xFF) << 16 | (data[12] & 0xFF) << 8 | (data[13] & 0xFF); //图片总长度
                int picSubNum = ((data[15] & 0xFF) << 8) | (data[16] & 0xFF); //图片分包数
            }
        }
    };


    private Context mContext;
    private OnBluetoothAction mOnBluetoothAction;
    private String TAG = "EJV3_TAIIC";
    private int devConnStatus = DataConfig.STATE_DISCONNECTED;
    private SppConnMgr sppConnMgr;
    private String deviceName = "TAIIC_EJV3_";
//    private PairedDeviceInfo connedDeviceInfo = new PairedDeviceInfo();
    private BluetoothDevice connectedDevices;
    private SPPEventListener sppEventListener = new SPPEventListener() {
        @Override
        public void onConnStatusChanged(int status) {
            Log.d(TAG, "onConnStatusChanged status=" + status);
            if (status == SppConnMgr.SPP_CONNECTED)
            {
                devConnStatus = DataConfig.STATE_CONNECTED;
                mOnBluetoothAction.onConnectSuccess(connectedDevices);
            }

            else if (status == SppConnMgr.SPP_DISCONNECTED)
            {
                devConnStatus = DataConfig.STATE_DISCONNECTED;
                mOnBluetoothAction.onDisConnect(connectedDevices);
            }
        }

        @Override
        public void onRecvData(byte[] data, int dataLen) {
            Log.d(TAG, "onRecvData, dataLen=" + dataLen);
            if(dataLen != -1)
            {
//                [fe 01 08 02 00 04 00 0e 12 1a 0a 2d] 电量
                if(dataLen== 12 && data[0] == -2 && data[1] == 1 && data[2] == 8 && data[3] == 2)
                {
                    byte[] targetBuffer = new byte[dataLen];
                    System.arraycopy(data, 0, targetBuffer, 0, dataLen);
                    Message message = handlerBattery.obtainMessage(MESSAGE_DATA_RECEIVED, targetBuffer.length, 0, targetBuffer);
                    handlerBattery.sendMessage(message);


                }
//                [FE, 04, 08, 30, 00, 02, 00, 60, 81, 5A] 模式
                else if(dataLen== 10 && data[0] == -2 && data[1] == 4 && data[2] == 8 && data[3] == 48)
                {
                    byte[] targetBuffer = new byte[dataLen];
                    System.arraycopy(data, 0, targetBuffer, 0, dataLen);
                    Message message = handlerUseMode.obtainMessage(MESSAGE_DATA_RECEIVED, targetBuffer.length, 0, targetBuffer);
                    handlerUseMode.sendMessage(message);



                }
//                [FE, 04, 08, 31, 00, 04, 00, 00, 00, 13, 81, 5A] 标签
                else if(dataLen== 12 && data[0] == -2 && data[1] == 4 && data[2] == 8 && data[3] == 49)
                {
                    byte[] targetBuffer = new byte[dataLen];
                    System.arraycopy(data, 0, targetBuffer, 0, dataLen);
                    Message message = handlerLabel.obtainMessage(MESSAGE_DATA_RECEIVED, targetBuffer.length, 0, targetBuffer);
                    handlerLabel.sendMessage(message);



                }
//                [FE, 04, 08, 28, 00, 0B, 00, 70, 00, 70, 00, 00, 49, 80, 00, 00, 13, 58, 4A] 图像类型
                else if(dataLen == 19 && data[0] == -2 && data[1] == 4 && data[2] == 8 && data[3] == 40)
                {
                    byte[] targetBuffer = new byte[dataLen];
                    System.arraycopy(data, 0, targetBuffer, 0, dataLen);
                    Message message = handlerCameraInfo.obtainMessage(MESSAGE_DATA_RECEIVED, targetBuffer.length, 0, targetBuffer);
                    handlerCameraInfo.sendMessage(message);



                }else if(dataLen == 9)
                {
                    String[] receive = byteToHex(data, dataLen); //byte数组转为string数组,16进制
                    Log.d(TAG, "onRecvData: ");
                }
                else
                {
                    // 发送数据到 Handler
                    byte[] targetBuffer = new byte[dataLen];
                    System.arraycopy(data, 0, targetBuffer, 0, dataLen);
                    Message message = handler.obtainMessage(MESSAGE_DATA_RECEIVED, targetBuffer.length, 0, targetBuffer);
                    handler.sendMessage(message);
                }
            }

        }
    };

//构造函数
    public BLESPPUtils(Context context, OnBluetoothAction onBluetoothAction)
    {
        mContext = context;
        mOnBluetoothAction = onBluetoothAction;
        sppConnMgr = new SppConnMgr(mContext, sppEventListener);
    }
//    使能蓝牙适配器
    public void enableBlvetooth()
    {
//        MyData.getInstance();
//        AllParam.initAllParam();

    }
//    设置已连接设备设备的名字，可以是前部分，比比较前8个字节
    public void setBtDeviceName(String btDeviceName)
    {
        deviceName = btDeviceName;

    }
//    获取符合要求的已连接设备，获取后会进行socket通信;
    public void getconnectedBtDevice()
    {
        //        PairedDeviceInfo pairedDevice = AllParam.getPairedDevInfo().getLastConnDevice();
        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
        try
        {
            //得到连接状态的方法
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            //打开权限
            method.setAccessible(true);
            int state = (int) method.invoke(BluetoothAdapter.getDefaultAdapter(), (Object[]) null);
            if (state == BluetoothAdapter.STATE_CONNECTED) {
                Log.i("EJV3_BLUETOOTH", "BluetoothAdapter.STATE_CONNECTED");
                Set<BluetoothDevice> devices = BluetoothAdapter.getDefaultAdapter().getBondedDevices(); //集合里面包括已绑定的设备和已连接的设备
                Log.i("EJV3_BLUETOOTH", "devices:" + devices.size());
                if(devices.size() > 0)
                {
                    for(BluetoothDevice device : devices)
                    {
                        boolean isDevice = compareFirstFourBytes(device.getName(), deviceName);
                        if(isDevice)
                        {
                            sppConnMgr.connectDevice(device.getAddress());
                            connectedDevices = device;
                        }
                    }
                }
            }


        }catch (NoSuchMethodException e)
        {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

//        List<PairedDeviceInfo> pairedDevice = AllParam.getPairedDevInfo().getPairedDevList();
//        for(PairedDeviceInfo deviceInfo : pairedDevice)
//        {
//            if(deviceInfo.isValidDevice() && compareFirstFourBytes(deviceInfo.getName(), deviceName))
//            {
//                connedDeviceInfo = deviceInfo;
//                sppConnMgr.connectDevice(deviceInfo.getMacAddr());
//
//            }
//        }
    }
//    关闭socket通道
    public void disConnectedBtDevice()
    {
        sppConnMgr.destory();
    }
    public void send(String strValue)
    {
        int keyValue = Integer.valueOf(strValue);
        byte[] data = new byte[1];
        data[0] = (byte) keyValue;

        CommandInfo cmd = new CommandInfo();
        cmd.setFrom(CommandInfo.DEVICE_APP);
        cmd.setTo(CommandInfo.DEVICE_MCU);
        cmd.setCommandID(CommandInfo.CMDID_KEY_VALUE_ISSUE);
        cmd.setCmdData(data);
        Log.d(TAG, "sendCommand");
        if (devConnStatus != DataConfig.STATE_CONNECTED) {
            Log.d(TAG, "devConnStatus(" + devConnStatus + ") != STATE_CONNECTED, return");
            return;
        }
        cmd.setFrom(CommandInfo.DEVICE_APP);
        byte[] framData = CommandDataAnalyze.packFrameData(cmd);
        sppConnMgr.sendData(framData, framData.length);
        mOnBluetoothAction.onSendBytes(data[0]);
    }

    private static boolean compareFirstFourBytes(String str1, String str2) {
        // 获取两个字符串的前 8 个字符
        String subStr1 = str1.length() >= 10 ? str1.substring(0, 10) : str1;
        String subStr2 = str2.length() >= 10 ? str2.substring(0, 10) : str2;

        // 比较前 8 个字符
        return subStr1.equals(subStr2);
    }
    private static String[] byteToHex(byte[] buffer, int len)
    {
        String[] hexArray = new String[len];
        for(int i =0; i < len; ++i)
        {
            // 转换为 16 进制
            String hexString = String.format("%02X", buffer[i] & 0xFF);
            hexArray[i] = hexString;
        }
//        for (byte b : buffer) {
//
//        }
        return hexArray;
    }
}
